package com.xebest.web.controller.storehouse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.config.ParamConfig;
import com.xebest.constant.XeConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.util.msg.XeVenStoreHouseMsg;
import com.xebest.web.form.XeVenStoreAllotForm;
import com.xebest.web.form.XeVenStoreAllotUpdateForm;
import com.xebest.web.form.XeVenStoreListForm;
import com.xebest.web.model.XeVenStoreAllotDetailEntity;
import com.xebest.web.model.XeVenStoreAllotEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenStoreAllotService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenStoreAllotView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调拨单相关操作
 *
 * @author 杜春静
 */

@RestController
@RequestMapping("allotManager")
public class XeVenStoreAllotController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenStoreAllotController.class);//日志记录类

    @Autowired
    XeVenStoreAllotService xeVenStoreAllotService;//调拨单业务类

    @Autowired
    private ParamConfig paramConfig;//获取公共配置信息

    /**
     * 查询调拨单列表信息
     *
     * @author 杜春静
     */
    @RequestMapping("queryStoreAllotList")
    public BaseResponse queryStoreAllotList(@RequestBody XeVenStoreAllotForm form) {

        log.info("查询调拨单列表请求参数为：", JSON.toJSONString(form));
        //下拉选择文本框的查询维度
        if (null != form.getSearchType()) {
            Integer queryFlag = form.getSearchType();
            String searchCondition = form.getSearchCondition();
            switch (queryFlag) {
                case 1:   //调拨单号
                    if (!StringUtils.isEmpty(searchCondition)) {
                        form.setAllotCode(searchCondition);
                    }
                    break;
                case 2:   //出库单号
                    if (!StringUtils.isEmpty(searchCondition)) {
                        form.setAllotOutOrder(searchCondition);
                    }
                    break;
                case 3:   //入库单号
                    if (!StringUtils.isEmpty(searchCondition)) {
                        form.setAllotInOrder(searchCondition);
                    }
                    break;
                case 4:   //商品名称
                    if (!StringUtils.isEmpty(searchCondition)) {
                        form.setProName(searchCondition);
                    }
                    break;
                default: //商品货号
                    if (!StringUtils.isEmpty(searchCondition)) {
                        form.setProNum(searchCondition);
                    }
                    break;
            }
        }
        //下拉选择时间段的搜索维度
        if (null != form.getSearchTimeType()) {
            Integer queryFlag = form.getSearchTimeType();
            String searchTimeStart = form.getSearchTimeStart();
            String searchTimeEnd = form.getSearchTimeEnd();
            if (!StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                if (!DateUtil.comparableTime(searchTimeStart, searchTimeEnd)) {
                    return sendAjaxError(XeVenOrderMsg.TIME_MSG);
                }
                String createDateEnd = form.getSearchTimeEnd();
                searchTimeEnd = createDateEnd + " 23:59:59";
            }

            switch (queryFlag) {
                case 1:   //创建时间
                    //创建时间默认为3个月
                    if (StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setCreateTimeStart(DateUtil.getFrontMonth(3));
                        form.setCreateTimeEnd(DateUtil.getDayLastTime(0));
                    }
                    if (StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setCreateTimeStart(DateUtil.strToNMonth(searchTimeEnd, -3));
                        form.setCreateTimeEnd(searchTimeEnd);
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setCreateTimeStart(searchTimeStart);
                        form.setCreateTimeEnd(DateUtil.strToNMonth(searchTimeStart, 3));
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setCreateTimeStart(searchTimeStart);
                        form.setCreateTimeEnd(searchTimeEnd);
                    }
                    break;
                case 2:   //出库时间
                    //出库时间默认为3个月
                    if (StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setSendTimeStart(DateUtil.getFrontMonth(3));
                        form.setSendTimeEnd(DateUtil.getDayLastTime(0));
                    }
                    if (StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setSendTimeStart(DateUtil.strToNMonth(searchTimeEnd, -3));
                        form.setSendTimeEnd(searchTimeEnd);
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setSendTimeStart(searchTimeStart);
                        form.setSendTimeEnd(DateUtil.strToNMonth(searchTimeStart, 3));
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setSendTimeStart(searchTimeStart);
                        form.setSendTimeEnd(searchTimeEnd);
                    }
                    break;
                default: //入库时间
                    //入库时间默认为3个月
                    if (StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setReceiptTimeStart(DateUtil.getFrontMonth(3));
                        form.setReceiptTimeEnd(DateUtil.getDayLastTime(0));
                    }
                    if (StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setReceiptTimeStart(DateUtil.strToNMonth(searchTimeEnd, -3));
                        form.setReceiptTimeEnd(searchTimeEnd);
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && StringUtils.isEmpty(searchTimeEnd)) {
                        form.setReceiptTimeStart(searchTimeStart);
                        form.setReceiptTimeEnd(DateUtil.strToNMonth(searchTimeStart, 3));
                    }
                    if (!StringUtils.isEmpty(searchTimeStart) && !StringUtils.isEmpty(searchTimeEnd)) {
                        form.setReceiptTimeStart(searchTimeStart);
                        form.setReceiptTimeEnd(searchTimeEnd);
                    }
                    break;
            }
        } else {
            form.setCreateTimeStart(DateUtil.getFrontMonth(3));
            form.setCreateTimeEnd(DateUtil.getDayLastTime(0));
        }

        // 拼装供应商code
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        //封装页面参数
        XePageInfo<XeVenStoreAllotView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("form", form);
        try {
            List<XeVenStoreAllotView> storeInfoList = this.xeVenStoreAllotService.queryStoreAllotList(paramMap);
            xePageInfo = new XePageInfo<XeVenStoreAllotView>(storeInfoList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actionList", storeInfoList);
            map.put("xePageInfo", xePageInfo);

            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("--------------查询调拨单列表 异常-{}------------------", e);
            return sendAjaxError();
        }
    }

    /**
     * 根据调拨单号查询调拨单商品明细
     *
     * @author 杜春静
     */
    @RequestMapping("queryAllotDetailList")
    public BaseResponse queryAllotDetailList(@RequestBody XeVenStoreAllotDetailEntity form) {

        log.info("--------------查询调拨单商品明细 start-------------------");
        log.info("查询调拨单列表请求参数为：", JSON.toJSONString(form));
        //1、验证参数
        if (form == null || form.getAllotCode() == null) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("allotCode", form.getAllotCode());
        paramMap.put("userCode", userInfo.getUserCode());
        try {
            List<XeVenStoreAllotDetailEntity> allotDetailList = this.xeVenStoreAllotService.listAllotDetailByParam(paramMap);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actionList", allotDetailList);
            String picServer = paramConfig.getImgUrl() + XeConstans.ERP_PRO_PIC_DIR;//图片服务器地址
            map.put("picServer", picServer);
            log.info("--------------查询调拨单商品明细列表 end-------------------");
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询调拨单商品明细列表" + e);
            return sendAjaxError();
        }
    }

    /**
     * 修改调拨单
     *
     * @author 杜春静
     */
    @RequestMapping("updateStoreAllot")
    public BaseResponse updateStoreAllot(@RequestBody @Validated XeVenStoreAllotUpdateForm form, BindingResult bindingResult) {
        log.info("修改调拨单请求参数为：{} ", JSON.toJSONString(form));
        //1、验证参数
        if (null == form || StringUtils.isEmpty(form.getAllotCode())) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (bindingResult.hasErrors()) {
            return sendAjaxError(bindingResult.getFieldError().getDefaultMessage());
        }
        XeVenStoreAllotEntity entity = new XeVenStoreAllotEntity();
        //前台获取数据并转换成实体
        String jsonString = JSON.toJSONString(form, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
        entity = JSON.parseObject(jsonString, XeVenStoreAllotEntity.class);
        //2、获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        entity.setUserCode(userInfo.getUserCode());
        entity.setModifyUser(userInfo.getLoginName());
        //3、输出结果
        int result = 0;
        try {
            result = xeVenStoreAllotService.updateStoreAllot(entity);
            if (result < 0) {
                return sendAjaxError("调拨单更新失败");
            }
            log.info("成功更新调拨单", result);
        } catch (Exception e) {
            log.error("修改调拨单异常：" + e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 审核调拨单
     *
     * @author 杜春静
     */
    @RequestMapping(value = "checkStoreAllot", method = RequestMethod.POST)
    public BaseResponse checkStoreAllot(@RequestBody XeVenStoreAllotEntity entity) {
        log.info("审核调拨单请求参数为：{} ", JSON.toJSONString(entity));
        //1、验证参数
        if (entity == null || StringUtils.isEmpty(entity.getAllotCode()) || entity.getAllotStatus() == null || entity.getAllotStatus() == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //2、获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode", userInfo.getUserCode());
        paramMap.put("allotCode", entity.getAllotCode());
        Integer allotStatus = entity.getAllotStatus();//调拨单状态
        //3、输出结果
        int result = 0;
        try {
            entity = this.xeVenStoreAllotService.queryStoreAllot(paramMap);
            if (null == entity) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            entity.setCheckUser(userInfo.getLoginName());
            entity.setModifyUser(userInfo.getLoginName());
            entity.setAllotStatus(allotStatus);
            result = xeVenStoreAllotService.checkStoreAllot(entity);
            if (result == 1000) {
                return sendAjaxError(XeVenStoreHouseMsg.ALLOT_STORE_NOT_ENOUGH);
            }
            if (result == 2000) {
                return sendAjaxError();
            }
            if (result <= 0) {
                log.info("调拨单审核失败！");
                return sendAjaxError(XeVenStoreHouseMsg.ALLOT_CHECK_FAIL_MSG);
            }
        } catch (Exception e) {
            log.error("调拨单审核异常{}：", e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 批量废弃调拨单
     *
     * @author 杜春静
     */
    @RequestMapping(value = "batchDiscardAllot", method = RequestMethod.POST)
    public BaseResponse batchDiscardAllot(@RequestBody XeVenStoreListForm entity) {
        log.info("批量废弃调拨单请求参数为：{} ", JSON.toJSONString(entity));
        //1、验证参数
        if (null == entity || null == entity.getAllotCodeS() || entity.getAllotCodeS().length <= 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        String[] allotCodes = entity.getAllotCodeS();
        if (allotCodes.length > 10) {
            return sendAjaxError(XeVenStoreHouseMsg.OPERATE_DARA_OVER_TEN);
        }
        //2、获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        //2、输出结果
        int result = 0;
        try {
            result = xeVenStoreAllotService.updateDiscardStoreAllot(allotCodes, userInfo);
            if (result < 0) {
                log.info("调拨单废弃失败");
                return sendAjaxError("调拨单废弃失败");
            }
            log.info("成功废弃调拨单", result);
        } catch (Exception e) {
            log.error("批量废弃调拨单异常：" + e);
            return sendAjaxError();
        } finally {
            log.info("======== 批量废弃调拨单结束 ========");
        }
        return sendAjaxOK();
    }

    /**
     * 添加调拨单
     *
     * @author 杜春静
     */
    @RequestMapping(value = "saveStoreAllot", method = RequestMethod.POST)
    public BaseResponse saveStoreAllot(@RequestBody @Validated XeVenStoreAllotUpdateForm form, BindingResult bindingResult) {
        log.info("添加调拨单调拨单请求参数为：{} ", JSON.toJSONString(form));
        //1、验证参数
        if (null == form.getAllotDetailList()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (bindingResult.hasErrors()) {
            return sendAjaxError(bindingResult.getFieldError().getDefaultMessage());
        }
        XeVenStoreAllotEntity entity = new XeVenStoreAllotEntity();
        //前台获取数据并转换成实体
        String jsonString = JSON.toJSONString(form, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
        entity = JSON.parseObject(jsonString, XeVenStoreAllotEntity.class);

        //2、获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        entity.setUserCode(userInfo.getUserCode());
        entity.setCreateUser(userInfo.getLoginName());
        entity.setModifyUser(userInfo.getLoginName());
        //3、输出结果
        int result = 0;
        try {
            result = xeVenStoreAllotService.saveStoreAllot(entity);
            if (result < 0) {
                log.info("添加调拨单失败");
                return sendAjaxError("添加调拨单失败");
            }
            log.info("成功添加调拨单", result);
        } catch (Exception e) {
            log.error("添加调拨单异常：" + e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 根据调拨单号查询调拨单信息包含商品明细
     *
     * @author 杜春静
     */
    @RequestMapping("queryStoreAllot")
    public BaseResponse queryStoreAllot(@RequestBody XeVenStoreAllotForm form) {
        //TODO 根据调拨单号查询调拨单
        log.info("根据调拨单号查询调拨单：", JSON.toJSONString(form));
        if (null == form || StringUtils.isEmpty(form.getAllotCode())) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取商户信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        //封装查询参数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode", userInfo.getUserCode());
        paramMap.put("allotCode", form.getAllotCode());
        try {
            XeVenStoreAllotEntity storeAllot = this.xeVenStoreAllotService.queryStoreAllot(paramMap);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actionList", storeAllot);
            String picServer = paramConfig.getImgUrl() + XeConstans.ERP_PRO_PIC_DIR;//图片服务器地址
            map.put("picServer", picServer);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("--------------根据调拨单号查询调拨单 异常-------------------" + e);
            return sendAjaxError();
        }
    }

}
  
